package zheezes.eisp;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

public class ImageRegistryFactory {
	public static final String IMAGE_KAIFA_LOGO = "kaifa.ico";
	public static final String IMAGE_COLLECT = "collect.ico";
	public static final String IMAGE_COMPUTE = "compute.ico";
	public static final String IMAGE_AUTOTASK = "autotask.ico";
	public static final String IMAGE_STAR = "star.jpg";
	
	/* this codes must be exist, even if it no of use */
	static {
		if (Display.getCurrent() == null) {
			Display.getDefault();
		}
	}

	public final Field[] filter() {
		List<Field> list = new ArrayList<Field>();
		for (Field field : ImageRegistryFactory.class.getFields()) {
			int modifier = field.getModifiers();
			if ((modifier & (Modifier.STATIC | Modifier.FINAL)) != 0) {
				if (field.getName().startsWith("IMAGE")) {
					list.add(field);
				}
			}
		}
		return list.toArray(new Field[0]);
	}

	public final void load(ImageRegistry registry, File dir) {
		if (dir.exists() && dir.isDirectory()) {
			Field[] fields = filter();
			for (Field field : fields) {
				URL url = null;
				String filename = "";
				try {
					filename = (String) field.get(null);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				try {
					url = new URL("file:" + dir.getAbsolutePath() + File.separator + filename);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}

				ImageDescriptor desc = ImageDescriptor.createFromURL(url);
				registry.put(filename, desc);
			}
		}
	}

	public final ImageRegistry create(File dir) {
		ImageRegistry registry = new ImageRegistry();
		load(registry, dir);
		return registry;
	}

	public static void main(String[] args) {
		ImageRegistry registry = new ImageRegistryFactory().create(new File("image"));
		ImageDescriptor desc = registry.getDescriptor(IMAGE_KAIFA_LOGO);
		Image image = desc.createImage();
		System.out.println(image.type == SWT.ICON);
	}
}
